aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/app/api/assets/[assetId]/route.ts
blob: 3bff79ba5794dfa3e090ef8c4c0e89eedcc3a9be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { createContextFromRequest } from "@/server/api/client";
import { and, eq } from "drizzle-orm";

import { assets } from "@hoarder/db/schema";
import { readAsset } from "@hoarder/shared/assetdb";

export const dynamic = "force-dynamic";
export async function GET(
  request: Request,
  { params }: { params: { assetId: string } },
) {
  const ctx = await createContextFromRequest(request);
  if (!ctx.user) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }

  const assetDb = await ctx.db.query.assets.findFirst({
    where: and(eq(assets.id, params.assetId), eq(assets.userId, ctx.user.id)),
  });

  if (!assetDb) {
    return Response.json({ error: "Asset not found" }, { status: 404 });
  }

  const { asset, metadata } = await readAsset({
    userId: ctx.user.id,
    assetId: params.assetId,
  });

  const range = request.headers.get("Range");
  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : asset.length - 1;

    // TODO: Don't read the whole asset into memory in the first place
    const chunk = asset.subarray(start, end + 1);
    return new Response(chunk, {
      status: 206, // Partial Content
      headers: {
        "Content-Range": `bytes ${start}-${end}/${asset.length}`,
        "Accept-Ranges": "bytes",
        "Content-Length": chunk.length.toString(),
        "Content-type": metadata.contentType,
      },
    });
  } else {
    return new Response(asset, {
      status: 200,
      headers: {
        "Content-Length": asset.length.toString(),
        "Content-type": metadata.contentType,
      },
    });
  }
}